﻿namespace Services.Implement;

/// <summary>
/// 登录日志服务
/// </summary>
public class LoginLogBLL(ISqlSugarClient db) : BaseBLL<LoginLog>(db), ILoginLogBLL
{
    private readonly ISqlSugarClient _db = db;

    /// <summary>
    /// 登录日志列表分页
    /// </summary>
    /// <returns></returns>
    public async Task<List<LoginLog>> QueryPageListAsync(LoginLogPageQueryRM pageQuery, RefAsync<int> count)
    {
        var resultList = new List<LoginLog>();
        var alogsLoginLogList = await ALOGSData.GetQueryLoginLogPage(pageQuery.Account, pageQuery.Name, "", Convert.ToDateTime(pageQuery.LoginTimeStart).ToString("yyyy-MM-dd HH:mm:ss"), Convert.ToDateTime(pageQuery.LoginTimeEnd).ToString("yyyy-MM-dd HH:mm:ss"), pageQuery.PageIndex, pageQuery.PageSize, count);
        if (alogsLoginLogList != null && alogsLoginLogList.Any())
        {
            var userIds = alogsLoginLogList.Select(x => x.UserId).ToList();

            var sessions = alogsLoginLogList.Select(x => x.Session).ToList();

            var loginLogList = await GetListAsync<LoginLog>(l => userIds.Contains(l.UserId) && sessions.Contains(l.Token));

            foreach (var alogsLoginLog in alogsLoginLogList)
            {
                var duration = loginLogList.FirstOrDefault(x => x.UserId == alogsLoginLog.UserId && x.Token == alogsLoginLog.Session) !=
                        null
                        ? loginLogList.FirstOrDefault(x => x.UserId == alogsLoginLog.UserId && x.Token == alogsLoginLog.Session)!.Duration
                            : 0;
                var loginLogVM = new LoginLog
                {
                    Account = alogsLoginLog.Uid,
                    Name = alogsLoginLog.Name,
                    RoleName = alogsLoginLog.RoleName,
                    Ip = alogsLoginLog.Ip,
                    LoginTime = Convert.ToDateTime(alogsLoginLog.Time),
                    Duration = duration <= 0 ? 1 : duration
                };
                resultList.Add(loginLogVM);
            }
        }
        return resultList;
    }

    /// <summary>
    /// 新建登录日志
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<bool> AddLoginLogAsync(AddLoginLogInput input)
    {
        var loginLog = MapperHelper.Mapper<LoginLog, AddLoginLogInput>(input);
        return await InsertAsync(loginLog);
    }

}